package zsc.ruanc.practicaltraining.service.Impl;


import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import zsc.ruanc.practicaltraining.exception.ApiException;
import zsc.ruanc.practicaltraining.mapper.Redis;
import zsc.ruanc.practicaltraining.mapper.UserMapper;
import zsc.ruanc.practicaltraining.model.domain.TUser;
import zsc.ruanc.practicaltraining.model.vo.EmailVo;
import zsc.ruanc.practicaltraining.model.vo.RabbitMQEmail;
import zsc.ruanc.practicaltraining.service.EmailService;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Random;

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private Redis redis;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Value("${email.code.content}")
    private String content;

    @Value("${email.subject}")
    private String subject;

    @Value("${image.path1}")
    private String imagePath1;

    @Value("${image.path2}")
    private String imagePath2;

    @Value("${image.path3}")
    private String imagePath3;

    @Value("${email.findPasswordContent}")
    private String findContent;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public int randCode() {
        Random rd = new Random();
        int code = rd.nextInt(9000) + 1000;
        return code;
    }

    @Override
    public int sendCode(EmailVo emailVo) {

        if (userMapper.checkEmail(emailVo.getEmail())) {
            throw new ApiException(-3);
        }


        int code = randCode();

        // 保存验证码
        redis.set(emailVo.getEmail(), code);

        // 邮件内容
        String text = String.format(content, emailVo.getUsername(), String.valueOf(code), "img");
        RabbitMQEmail email = new RabbitMQEmail(emailVo.getEmail(), text, imagePath1);

        // 发消息
        rabbitTemplate.convertAndSend("fanout_blog", "email",email);

        return code;
    }



    @Override
    public int findPassword(String email) {
        if (!userMapper.checkEmail(email)) {
            throw new ApiException(-5);
        }


        int code = randCode();

        // 保存验证码
        redis.set(email, code);

        // 邮件内容
        String text = String.format(findContent, String.valueOf(code), "img");
        RabbitMQEmail rabbitMQEmail = new RabbitMQEmail(email, text, imagePath2);

        // 发消息
        rabbitTemplate.convertAndSend("fanout_blog", "email",rabbitMQEmail);
        return code;

    }

    @Override
    public int updateEmail(String email) {
        if (userMapper.checkEmail(email)) {
            throw new ApiException(-3);
        }


        int code = randCode();

        // 保存验证码
        redis.set(email, code);

        // 邮件内容
        String text = String.format(findContent, String.valueOf(code), "img");
        RabbitMQEmail rabbitMQEmail = new RabbitMQEmail(email, text, imagePath3);

        // 发消息
        rabbitTemplate.convertAndSend("fanout_blog", "email",rabbitMQEmail);
        return code;
    }

    @Override
    public boolean adminSend(Integer id, String text) {
        TUser user = userMapper.selectById(id);
        if (user == null) {
            throw new ApiException(-5);
        }


        RabbitMQEmail rabbitMQEmail = new RabbitMQEmail(user.getEmail(), text, imagePath3);

        // 发消息
        rabbitTemplate.convertAndSend("fanout_blog", "email",rabbitMQEmail);
        return true;
    }




    @RabbitListener(queues = "fanout_queue_email")
    public void sendEmailCode(RabbitMQEmail email) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(email.getTo());
            helper.setSubject(subject);
            helper.setText(email.getContent(), true);
            // 判断是否需要发送图片
            if (email.getPath() != null) {
                FileSystemResource res = new FileSystemResource(new File(email.getPath()));
                helper.addInline("img", res);
            }

            mailSender.send(message);
        } catch (MessagingException e) {
            System.out.println("发送邮件失败" + email);
        }
    }


}
